package com.xcc.common;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author frosty
 * @description
 * @date 2019-11-12 12:14:07
 */

public class BeanMaper {

    public static <T> T   mapToObj(Map<String, Object> map, Class<T> beanClass) throws Exception {
        T obj = beanClass.newInstance();
        if (map == null||map.keySet().size()==0) {
          return  obj;
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
           try {
               setter.invoke(obj, map.get(property.getName()));
           }catch (Exception e){
               e.printStackTrace();
           }
            }
        }

        return obj;
    }
}